package com.motorhome.h5.service.impl;

import com.motorhome.base.cache.MemcachedCache;
import com.motorhome.base.session.CookieSession;
import com.motorhome.base.util.HttpClientUtil;
import com.motorhome.base.util.JsonUtil;
import com.motorhome.base.util.Result;
import com.motorhome.base.util.StringUtil;
import com.motorhome.h5.common.statics.H5Statics;
import com.motorhome.h5.dao.LoginDao;
import com.motorhome.h5.domain.User;
import com.motorhome.h5.service.LoginService;
import com.motorhome.h5.service.WeixinService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Objects;

/**
 * @author: John
 */
@Service
public class WeixinServiceImpl implements WeixinService {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private MemcachedCache cache;

    @Autowired
    private LoginDao loginDao;

    @Autowired
    private LoginService loginService;

    @Override
    public void wxLogin(HttpServletRequest request, HttpServletResponse response) {

        try {

            //获取code
            String code = request.getParameter("code");
            if (StringUtil.isBlank(code)) {
                response.sendRedirect(H5Statics.MP_AUTHORIZE_URL
                                .replace("APPID", H5Statics.MP_APPID)
                                .replace("REDIRECT_URI", H5Statics.MP_REDIRECT_URL)
                                .replace("SCOPE", "snsapi_base")
                );
                return;
            }

            //获取openId
            String accessTokenStr = new HttpClientUtil().post(H5Statics.MP_ACCESSTOKEN_URL
                    .replace("APPID", H5Statics.MP_APPID)
                    .replace("SECRET", H5Statics.MP_APPSECRET)
                    .replace("CODE", code),
                    "");

            //用户已绑定跳首页，用户未绑定跳登录页绑定用户
            if (!StringUtil.isBlank(accessTokenStr)) {
                Map accessToken = JsonUtil.fromJson(accessTokenStr, Map.class);
                Object openId = accessToken.get("openid");
                if (openId != null) {
                    User user = loginDao.getUserByOpenId(openId.toString());
                    if (user != null) {

                        //设置会员信息
                        loginService.setUserVipInfo(user);

                        //登录成功，写入Session
                        cache.set("H5_USER_" + user.getId(), user, "24h");
                        CookieSession session = new CookieSession(request, response, H5Statics.SESSION_KEY);
                        session.put("uid", "" + user.getId());
                        session.flush(response);
                        response.sendRedirect(request.getContextPath() + "/h5/home/index");
                    } else {
                        response.sendRedirect(request.getContextPath() + "/h5/login/login?openId=" + openId);
                    }
                    return;
                }
            }

        } catch (Exception e) {
            logger.error("微信登录跳转异常", e);
        }

    }

}
